//
//  ViewController.m
//  Tom
//
//  Created by 解晓东 on 15/11/16.
//  Copyright (c) 2015年 sasa. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *tom;

@end

@implementation ViewController

/*
 重构-抽取代码
 1/将重复代码复制到新的方法中
 2/根据需要调整参数
 */
- (void)tomAnimation:(NSString *)name count:(NSInteger)count {
    // 如果动画中，不执行
    if ([self.tom isAnimating]) {
        return ;
    }
    // 动画图片的数组
    NSMutableArray *arrayM = [NSMutableArray array];
    
    // 添加动画播放的图片
    for (int i = 0; i < count; ++i) {
        // 图像名称
        NSString *imageName = [NSString stringWithFormat:@"%@_%02d.jpg", name, i]; // 确保格式eat_01.jpg
        NSLog(@"%@", imageName);
        // UIImage *image = [UIImage imageNamed:imageName]; // 会内存叠加
        NSString *path = [[NSBundle mainBundle] pathForResource:imageName ofType:nil];
        UIImage *image = [UIImage imageWithContentsOfFile:path];
        
        [arrayM addObject:image];
    }
    // 设置动画数组
    self.tom.animationImages = arrayM;
    // 重复一次
    self.tom.animationRepeatCount = 1;
    // 动画时长
    self.tom.animationDuration = self.tom.animationImages.count * 0.075;
    // 开始动画
    [self.tom startAnimating];
    
    // 动画结束之后，清理动画数组
    // 一段时间之后执行clearup方法
    [self performSelector:@selector(clearup) withObject:nil afterDelay:self.tom.animationDuration];
}

- (void)clearup {
    // self.tom.animationImages = nil;
    [self.tom setAnimationImages:nil];
}

// 晕倒
- (IBAction)knockout:(id)sender {
    [self tomAnimation:@"knockout" count:81];
}

// 吃鸟
- (IBAction)eatBird:(id)sender {
    [self tomAnimation:@"eat" count:40];
}

// 打镲
- (IBAction)cymbal:(id)sender {
    [self tomAnimation:@"cymbal" count:13];
}

// 放屁
- (IBAction)fart:(id)sender {
    [self tomAnimation:@"fart" count:28];
}

// 抓玻璃
- (IBAction)scratch:(id)sender {
    [self tomAnimation:@"scratch" count:56];
}

// 扔蛋糕
- (IBAction)pie:(id)sender {
    [self tomAnimation:@"pie" count:24];
}

// 喝牛奶
- (IBAction)drink:(id)sender {
    [self tomAnimation:@"drink" count:81];
}

// 左脚
- (IBAction)footLeft:(id)sender {
    [self tomAnimation:@"footLeft" count:30];
}

// 右脚
- (IBAction)footRight:(id)sender {
    [self tomAnimation:@"footRight" count:30];
}

// 肚子
- (IBAction)stomach:(id)sender {
    [self tomAnimation:@"stomach" count:34];
}

// 胸
- (IBAction)angry:(id)sender {
    [self tomAnimation:@"angry" count:26];
}

@end
